<?php
require_once 'auth.php';
requireAdmin();

$conn = dbConnect();

// 处理用户操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete'])) {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param('i', $_POST['user_id']);
        $stmt->execute();

        // 记录操作日志
        $logStmt = $conn->prepare("INSERT INTO operation_logs (user_id, operation_type, target_id, details) VALUES (?, 'delete', ?, ?)");
        $logDetails = '删除用户ID：' . $_POST['user_id'];
        $logStmt->bind_param('iis', $_SESSION['user_id'], $_POST['user_id'], $logDetails);
        $logStmt->execute();
    } else {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $role = $_POST['role'];

        if ($_POST['action'] === 'edit') {
            $stmt = $conn->prepare("UPDATE users SET username=?, password=?, role=? WHERE id=?");
            $stmt->bind_param('sssi', $username, $password, $role, $_POST['user_id']);
        } else {
            $stmt = $conn->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
            $stmt->bind_param('sss', $username, $password, $role);
        }
        $stmt->execute();

        // 记录操作日志
        $operationType = ($_POST['action'] === 'edit') ? 'update' : 'create';
        $logDetails = ($_POST['action'] === 'edit')
            ? '修改用户：' . $username
            : '新建用户：' . $username;
        $logStmt = $conn->prepare("INSERT INTO operation_logs (user_id, operation_type, target_id, details) VALUES (?, ?, ?, ?)");
        $targetId = ($_POST['action'] === 'edit') ? $_POST['user_id'] : $conn->insert_id;
        $logStmt->bind_param('isis', $_SESSION['user_id'], $operationType, $targetId, $logDetails);
        $logStmt->execute();
    }
}

// 分页参数
$itemsPerPage = 10; // 每页显示的记录数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;// 当前页码
$offset = ($page - 1) * $itemsPerPage; // 偏移量

// 获取用户总数
$totalUsers = $conn->query("SELECT COUNT(id) as total FROM users")->fetch_assoc()['total'];
$totalPages = ceil($totalUsers / $itemsPerPage); // 总页数

// 获取当前页的用户列表
$users = $conn->query("SELECT id, username, role FROM users LIMIT $offset, $itemsPerPage");
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用户管理</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
</head>

<body class="layout-fluid layout-vertical"> <!-- 统一body类 -->
    <?php include 'navbar.php'; ?>
    <div class="page">
        <div class="container-fluid">
            <div class="card mt-3">
                <div class="card-header">
                    <h3 class="card-title">用户管理</h3>
                    <button class="btn btn-primary ms-auto" data-bs-toggle="modal" data-bs-target="#userModal">
                        新建用户
                    </button>
                </div>
                <div class="card-body"> <!-- 添加card-body包裹表格 -->
                    <div class="table-responsive">
                        <table class="table table-vcenter table-hover">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>角色</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($user = $users->fetch_assoc()): ?>
                                <tr>
                                    <td><?= htmlspecialchars($user['username']) ?></td>
                                    <td><?= htmlspecialchars($user['role']) ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-icon" data-bs-toggle="modal"
                                            data-bs-target="#userModal"
                                            data-userid="<?= $user['id'] ?>"
                                            data-username="<?= $user['username'] ?>"
                                            data-role="<?= $user['role'] ?>">
                                            编辑
                                        </button>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                            <button type="submit" name="delete" class="btn btn-sm btn-icon" onclick="return confirm('确定删除该用户吗？')">删除</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <!-- 分页导航 -->
                <?php include 'pagination.php'; ?>
                </div> <!-- 关闭card-body -->
            </div>
        </div>
    </div>

    <!-- 用户编辑弹窗 -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <form method="post" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">用户信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="user_id" value="">

                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">角色</label>
                        <select name="role" class="form-select" required>
                            <option value="admin">管理员</option>
                            <option value="user">普通用户</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/dist/js/tabler.min.js"></script>
    <script>
        document.getElementById('userModal').addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            if (button.dataset.userid) {
                this.querySelector('input[name="action"]').value = 'edit';
                this.querySelector('input[name="user_id"]').value = button.dataset.userid;
                this.querySelector('input[name="username"]').value = button.dataset.username;
                this.querySelector('select[name="role"]').value = button.dataset.role;
            }
        });
    </script>
</body>

</html>